#!/bin/bash

trapFunction () {
  echo Exiting
}

mkdir -p ~/workspace/XML/ShellScripts/ForQUT
mkdir -p ~/workspace/XML/ShellScripts/ForQUT/JsonXML
mkdir -p ~/workspace/XML/ShellScripts/ForQUT/RifCs

read -p "Do you want to retrieve json from QUT before transforming -'Y' for yes ('N' will transform only)?  " choice
echo    # (optional) move to a new line
if [[ $choice =~ ^[Yy]$ ]]
then
  echo Retrieving json from QUT
  rm ~/workspace/XML/ShellScripts/ForQUT/JsonXML/*
  python ~/workspace/XML/ShellScripts/CKAN_API3_JsonToXML.py --identifierListURI  http://130.56.252.146/api/3/action/package_list --descriptionByIdentifierURI " http://130.56.252.146/api/3/action/package_show?id=%s" --outputDirectory ForQUT
fi

rm ~/workspace/XML/ShellScripts/ForQUT/RifCs/*

rm ~/workspace/XML/ShellScripts/ForQUT/RifCs/QUTRegistryObjects.xml
echo '<registryObjects xmlns:xs="http://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns="http://ands.org.au/standards/rif-cs/registryObjects"
                 xsi:schemaLocation="http://ands.org.au/standards/rif-cs/registryObjects http://services.ands.org.au/documentation/rifcs/schema/registryObjects.xsd">' >> ~/workspace/XML/ShellScripts/ForQUT/RifCs/QUTRegistryObjects.xml


trap trapFunction EXIT
trap 'exit 127' INT

ls ~/workspace/XML/ShellScripts/ForQUT/JsonXML | while read f; do
    fileNamePath="~/workspace/XML/ShellScripts/ForQUT/JsonXML/""$f"
    fileNameNoExtension=${f%.*}
    echo File: $fileNamePath
    echo Transforming $fileNamePath
    echo java -jar ~/workspace/XML/XSLT/saxon9he.jar ~/workspace/XML/ShellScripts/ForQUT/JsonXML/"$f" ~/workspace/XML/XSLT/json_To_RIFCS/QUT/QUT_json_to_rif-cs.xsl > ~/workspace/XML/ShellScripts/ForQUT/RifCs/$fileNameNoExtension"_rif-cs.xml" 
    java -jar ~/workspace/XML/XSLT/saxon9he.jar \
        ~/workspace/XML/ShellScripts/ForQUT/JsonXML/"$f" \
        ~/workspace/XML/XSLT/json_To_RIFCS/QUT/QUT_json_to_rif-cs.xsl \
        > ~/workspace/XML/ShellScripts/ForQUT/RifCs/$fileNameNoExtension"_rif-cs.xml" 
    echo XML written to ~/workspace/XML/ShellScripts/ForQUT/RifCs/$fileNameNoExtension"_rif-cs.xml"

    cat ~/workspace/XML/ShellScripts/ForQUT/RifCs/$fileNameNoExtension"_rif-cs.xml" >> ~/workspace/XML/ShellScripts/ForQUT/RifCs/QUTRegistryObjects.xml
   
done

 echo '</registryObjects>' >> ~/workspace/XML/ShellScripts/ForQUT/RifCs/QUTRegistryObjects.xml












